#include "PlayManager.h"


#include "../../Objects/Ghost/Play/GhostAdjust.h"
#include "../../Objects/Ghost/Play/GhostSelect.h"

#include "../Level/LevelManager.h"
#include "Layers/PlayGhostLayer.h"
#include "Layers/PlayResultLayer.h"
#include "Layers/PlayCongratulationsLayer.h"
#include "../../Player/PlayerInfo.h"
#include "../../Data/LevelData.h"
#include "../../Data/GameData.h"
#include "../../Support/GameSupport.h"
#include "../../Framework/SceneManager.h"
#include "../../Framework/SoundManager.h"

EGameStatus PlayManager::m_EGameStatus = EGameStatus::kGhostStatus_None;
bool PlayManager::m_isTutorial = false;

cocos2d::Scene* PlayManager::createScene()
{
    auto scene = Scene::create();
    auto layer = PlayManager::create();
    layer->initialize();
    scene->addChild(layer);
    return scene;
}

PlayManager::~PlayManager()
{
	CC_SAFE_DELETE(m_timeline);
	CC_SAFE_RELEASE_NULL(m_handTutorial);
}

// on "init" you need to initialize your instance
bool PlayManager::init()
{
    //////////////////////////////
    // 1. super init first
    if (!Layer::init())
    {
        return false;
    }
    
    setKeypadEnabled(true);
    
    m_screenSize = Director::getInstance()->getVisibleSize();
    
    return true;
}

void PlayManager::initBackground()
{
    Sprite* background = nullptr;
    switch (m_gameMode) {
        case kMode_Easy:
            background = Sprite::create("bg_easy.png");
            break;
        case kMode_Normal:
            background = Sprite::create("bg_normal.png");
            break;
        case kMode_Hard:
            background = Sprite::create("bg_hard.png");
            break;
        default:
            break;
    }

    
    float scaleX = m_screenSize.width / background->getContentSize().width;
    float scaleY = m_screenSize.height / background->getContentSize().height;
    background->setScale(scaleX, scaleY);
    //  cocos2d::Vector<Node*> list = node->getChildren();
    background->setAnchorPoint(Vec2(0.5f, 0.5f));
    background->setPosition(Vec2(m_screenSize.width / 2, m_screenSize.height / 2));
    this->addChild(background);
}

void PlayManager::initialize()
{
    m_gameMode = LevelManager::s_mode;
	m_isOpenSetting = false;

    this->removeAllChildren();
    initBackground();
    initLayer();
    
    if(!PlayerInfo::getInstance()->getPlayedTutorial(m_gameMode))
    {
        PlayManager::m_isTutorial = true;
        m_handTutorial = Sprite::create("hand.png");
        m_handTutorial->retain();
        m_handTutorial->runAction(RepeatForever::create(Sequence::create(ScaleTo::create(0.2f, 1.1f),ScaleTo::create(0.2f, 0.8f), NULL)));
    }
    else
        PlayManager:m_isTutorial = false;
    m_currIndexEquation = 0;
    
	std::map<int, LevelData>::iterator it;
    
    it = GameData::getInstance()->dataMode.find(LevelManager::s_ID);
    m_playType = it->second.Type;
    m_time = it->second.Time;
//    switch (m_gameMode)
//    {
//        case kMode_Easy:
//			it = GameData::getInstance()->easyMode.find(LevelManager::s_ID);
//			m_playType = it->second.Type;
//			m_time = it->second.Time;
//            break;
//        case kMode_Normal:
//			it = GameData::getInstance()->normalMode.find(LevelManager::s_ID);
//			m_playType = it->second.Type;
//			m_time = it->second.Time;
//            break;
//        case kMode_Hard:
//			it = GameData::getInstance()->hardMode.find(LevelManager::s_ID);
//			m_playType = it->second.Type;
//			m_time = it->second.Time;
//            break;
//    }

	m_valueTimeBar = 1.0f * 100.0f / m_time;
	m_tempTime = m_time;
    if (m_playType == EPlayType::kType_Adjust)
    {
        m_Cloud = static_cast<Button*>(m_PlayAdjustLayer->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_Cloud))));
        m_Cloud->setAnchorPoint(Vec2(0.5f,0.5f));
        
        m_Cloud->addClickEventListener(CC_CALLBACK_1(PlayManager::Clound_Click,this));
        //std::string tet= m_Clound->getTitleText();
        
        Button* btnSettings = static_cast<Button*>(m_PlayAdjustLayer->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_btnSetting))));
        
        m_loadingBar = static_cast<LoadingBar*>(m_PlayAdjustLayer->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_TimeBarBG)))
			->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_TimeBarFG))));
		m_timePanel = static_cast<Button*>(m_PlayAdjustLayer->getChildByName("timePanel"));
		m_timePanel->setTitleText(String::createWithFormat("%d", m_tempTime)->getCString());

        auto func = CallFuncN::create(CC_CALLBACK_1(PlayManager::calculateTimePlay, this));
		m_loadingBar->runAction(RepeatForever::create(Sequence::create(DelayTime::create(1.0f), func, NULL)));
        
        OpenPlayAdjustLayer();
    }
    else if (m_playType == EPlayType::kType_Select)
    {
        m_Cloud = static_cast<Button*>(m_PlaySelectLayer->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_Cloud))));
        m_Cloud->setAnchorPoint(Vec2(0.5f, 0.5f));
        Button* btnSettings = static_cast<Button*>(m_PlaySelectLayer->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_btnSetting))));
        
        m_loadingBar = static_cast<LoadingBar*>(m_PlaySelectLayer->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_TimeBarBG)))
			->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_TimeBarFG))));
		m_timePanel = static_cast<Button*>(m_PlaySelectLayer->getChildByName("timePanel"));
		m_timePanel->setTitleText(String::createWithFormat("%d", m_tempTime)->getCString());

        auto func = CallFunc::create(std::bind(&PlayManager::calculateTimePlay, this, m_loadingBar));
		m_loadingBar->runAction(RepeatForever::create(Sequence::create(DelayTime::create(1.0f), func, NULL)));
        
        OpenPlaySelectLayer();
    }
    if(m_isTutorial)
        playTutorial();
}

void PlayManager::reload()
{
    Node* resultLayer = this->getChildByTag(EPlayLayer::kPlayLayer_Result);
    if(resultLayer != nullptr)
        resultLayer->removeFromParent();
	m_Cloud->removeAllChildren();
    m_CongratulationsLayer->setVisible(false);
	m_isOpenSetting = false;
    if(m_gameMode == EGameMode::kMode_Hard)
    {
        Vector<Node*> children  = m_nodeGhostPlay->getChildren();
        int rows  = children.size();
        for(int i  = 0 ; i < rows; i++)
        {
            Node* row  = children.at(i);
            Vector<Node*> listNode = row->getChildren();
            int size = listNode.size();
            for(int j = 0 ; j < size;j++)
            {
                
                GhostSelect* ghost = (GhostSelect*)(listNode.at(j)->getChildren().at(0));
                ghost->removeFromParent();
                ghost->release();
            }
        }
    }
    else
        this->m_nodeGhostPlay->removeAllChildren();
    
    
    
//    initBackground();
//    initLayer();

	
		
	

    if(!PlayerInfo::getInstance()->getPlayedTutorial(m_gameMode))
    {
        PlayManager::m_isTutorial = true;
		if (m_handTutorial->getParent() != nullptr)
		{
			m_handTutorial->removeFromParent();
			m_handTutorial->release();
		}
        m_handTutorial = Sprite::create("hand.png");
        m_handTutorial->retain();
    }
	else
	{
		PlayManager:m_isTutorial = false;
		
	}
    
	m_valueTimeBar = 1.0f * 100.0f / m_time;
	m_tempTime = m_time;
    if (m_playType == EPlayType::kType_Adjust)
    {
        m_Cloud = static_cast<Button*>(m_PlayAdjustLayer->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_Cloud))));
        m_Cloud->setAnchorPoint(Vec2(0.5f,0.5f));
        
        m_Cloud->addClickEventListener(CC_CALLBACK_1(PlayManager::Clound_Click,this));
        //std::string tet= m_Clound->getTitleText();
        
        Button* btnSettings = static_cast<Button*>(m_PlayAdjustLayer->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_btnSetting))));
        
        m_loadingBar = static_cast<LoadingBar*>(m_PlayAdjustLayer->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_TimeBarBG)))
			->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_TimeBarFG))));
		m_timePanel = static_cast<Button*>(m_PlayAdjustLayer->getChildByName("timePanel"));
		m_timePanel->setTitleText(String::createWithFormat("%d", m_tempTime)->getCString());

        auto func = CallFunc::create(std::bind(&PlayManager::calculateTimePlay, this, m_loadingBar));
		m_loadingBar->runAction(RepeatForever::create(Sequence::create(DelayTime::create(1.0f), func, NULL)));

        OpenPlayAdjustLayer();
    }
    else if (m_playType == EPlayType::kType_Select)
    {
        m_Cloud = static_cast<Button*>(m_PlaySelectLayer->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_Cloud))));
        m_Cloud->setAnchorPoint(Vec2(0.5f, 0.5f));
        Button* btnSettings = static_cast<Button*>(m_PlaySelectLayer->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_btnSetting))));
        
        m_loadingBar = static_cast<LoadingBar*>(m_PlaySelectLayer->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_TimeBarBG)))
			->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_TimeBarFG))));
		m_timePanel = static_cast<Button*>(m_PlaySelectLayer->getChildByName("timePanel"));
		m_timePanel->setTitleText(String::createWithFormat("%d", m_tempTime)->getCString());

        auto func = CallFunc::create(std::bind(&PlayManager::calculateTimePlay, this, m_loadingBar));
		m_loadingBar->runAction(RepeatForever::create(Sequence::create(DelayTime::create(1.0f), func, NULL)));
        
        OpenPlaySelectLayer();
    }
    m_loadingBar->setPercent(100);
    if(m_isTutorial)
        playTutorial();
}
void PlayManager::clearCache()
{
    m_list_EquationRoot.clear();
    m_list_EquationResult.clear();
    m_list_AnswerStatus.clear();
    m_list_score.clear();
    m_list_star.clear();
    m_currIndexEquation = 0;
}


void PlayManager::initLayer()
{
	auto node = CSLoader::getInstance()->createNode("GameScene.csb");
    float scale = m_screenSize.height / node->getContentSize().height;
    kScale = scale;
    node->setScale(scale);
    
    m_PlaySelectLayer = node->getChildByName(std::string(GameSupport::getTextPlayLayer(EPlayLayer::kPlayLayer_Select)));
    
    m_PlayAdjustLayer = node->getChildByName(std::string(GameSupport::getTextPlayLayer(EPlayLayer::kPlayLayer_Adjust)));
    m_btnIncrease = static_cast<Button*>(m_PlayAdjustLayer->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_btnIncrease))));
    m_btnDecrease = static_cast<Button*>(m_PlayAdjustLayer->getChildByName(std::string(GameSupport::getTextPlayComponent(EPlayComponent::kPlayComponent_btnDecrease))));
    
    m_btnIncrease->setTitleText("+1");
    m_btnDecrease->setTitleText("-1");
    m_btnIncrease->setTitleFontName(kFont_Comica_BD);
    m_btnDecrease->setTitleFontName(kFont_Comica_BD);
    m_btnIncrease->setTitleFontSize(100);
    m_btnDecrease->setTitleFontSize(100);
    m_btnIncrease->addClickEventListener(CC_CALLBACK_1(PlayManager::IncreaseGhost, this));
    m_btnDecrease->addClickEventListener(CC_CALLBACK_1(PlayManager::DecreaseGhost, this));
    
    
	m_CongratulationsLayer = CSLoader::getInstance()->createNode("CongratulationLayer.csb");
    node->addChild(m_CongratulationsLayer);
    
    m_ResultLayer = node->getChildByName(std::string(GameSupport::getTextPlayLayer(EPlayLayer::kPlayLayer_Result)));
    
    m_CongratulationsLayer->setVisible(false);
    m_ResultLayer->setVisible(false);
    node->setAnchorPoint(Vec2(0.5f, 0.5f));
    
    node->setPosition(m_screenSize.width / 2, m_screenSize.height / 2);
    
    this->addChild(node);

	m_timeline = CSLoader::createTimeline("GameScene.csb");
	m_timeline->retain();
	node->runAction(m_timeline);
}

void PlayManager::initSetting(Node* nodeRoot)
{
	m_btnSetting = dynamic_cast<Button*>(nodeRoot->getChildByName("btnSettings"));
	m_pnlSetting = dynamic_cast<Node*>(nodeRoot->getChildByName("clipSetting")->getChildByName("pnl_settings"));
	m_pnlSetting->setVisible(false);

	//setting
	Button* btnSetting = dynamic_cast<Button*>(m_btnSetting);
	btnSetting->addClickEventListener(CC_CALLBACK_1(PlayManager::tapSetting, this));

	// Help - sound - music
	Button* btnHelp = dynamic_cast<Button*>(m_pnlSetting->getChildByName("btnHelp"));
	Button* btnAudio = dynamic_cast<Button*>(m_pnlSetting->getChildByName("btnAudio"));
	Button* btnMusic = dynamic_cast<Button*>(m_pnlSetting->getChildByName("btnMusic"));

	btnHelp->addClickEventListener(CC_CALLBACK_1(PlayManager::tapHelp, this));
	btnAudio->addClickEventListener(CC_CALLBACK_1(PlayManager::tapSound, this));
	btnMusic->addClickEventListener(CC_CALLBACK_1(PlayManager::tapMusic, this));
}

void PlayManager::OpenPlaySelectLayer()
{
    m_PlaySelectLayer->setVisible(true);
    m_PlayAdjustLayer->setVisible(false);
    m_CongratulationsLayer->setVisible(false);
    m_ResultLayer->setVisible(false);
    Node* resultLayer = this->getChildByTag(EPlayLayer::kPlayLayer_Result);
    if(resultLayer != nullptr)
        resultLayer->removeFromParent();
    initGame();
    initGhost();
	initSetting(m_PlaySelectLayer);
    m_EGameStatus = EGameStatus::kGhostStatus_None;
    
    //m_currStar = 3;
    this->scheduleUpdate();
}

void PlayManager::OpenPlayAdjustLayer()
{
    m_PlayAdjustLayer->setVisible(true);
    m_PlaySelectLayer->setVisible(false);
    m_CongratulationsLayer->setVisible(false);
    m_ResultLayer->setVisible(false);
    Node* resultLayer = this->getChildByTag(EPlayLayer::kPlayLayer_Result);
    if(resultLayer != nullptr)
        resultLayer->removeFromParent();
    initGame();
    initGhost();
	initSetting(m_PlayAdjustLayer);
    m_EGameStatus = EGameStatus::kGhostStatus_None;
    //m_currStar = 3;
    checkVisibleButton();
    this->scheduleUpdate();
}

void PlayManager::initGhost()
{
    PlayGhostLayer* layer = (PlayGhostLayer*)this->getChildByTag(EPlayLayer::kPlayLayer_Ghost);
    
        layer = new PlayGhostLayer(m_screenSize);
        layer->setPosition(Vec2::ZERO);
   
        this->addChild(layer);
    
    
    

    if (m_playType == EPlayType::kType_Adjust)
    {
        int numGhostStart = 0;
        numGhostStart = GameData::getInstance()->dataMode.find(LevelManager::s_ID)->second.listExpression[m_currIndexEquation].NumGhostStart;

        
        int answer = m_list_EquationRoot.at(m_currIndexEquation).Answer;

        
        m_nodeGhostPlay = m_PlayAdjustLayer->getChildByName("nodeNormal");
        
        Label* label = (Label*)m_Cloud->getChildByTag(EPlayComponent::kPlayComponent_Equation);
                if(m_gameMode == EGameMode::kMode_Easy)
        {
            int a= m_list_EquationRoot.at(m_currIndexEquation).a;
            int b= m_list_EquationRoot.at(m_currIndexEquation).b;
            
            int visibleGhost1 = 0;
            int visibleGhost2 = 0;
            do
            {
                visibleGhost1 = random(0,a);
                visibleGhost2 = random(0,b);
            }while(visibleGhost1 + visibleGhost2 == GamePlayConfig::GetInstance()->m_hiddenNumber);
            GamePlayConfig::GetInstance()->m_selectNumber = visibleGhost1 + visibleGhost2;


            layer->initAdjustPlayTwoCol(m_nodeGhostPlay,a,b, visibleGhost1,visibleGhost2);
        }
        else
        {
            int visibleGhost;
            int min = answer - m_list_EquationRoot.at(m_currIndexEquation).b == 0? 1 : m_list_EquationRoot.at(m_currIndexEquation).b;
            do
            {
                visibleGhost = random(min,numGhostStart);
                
            }while(visibleGhost == answer);
            GamePlayConfig::GetInstance()->m_selectNumber = visibleGhost;
            
            layer->initAdjustPlayOneCol(m_nodeGhostPlay,numGhostStart, visibleGhost);

        }
    }
    else
    {
        int numGhostStart = 0;
        
          numGhostStart = GameData::getInstance()->dataMode.find(LevelManager::s_ID)->second.listExpression[m_currIndexEquation].NumGhostStart;

        GamePlayConfig::GetInstance()->m_selectNumber = -1;
        auto str = cocos2d::String::createWithFormat("%s%d", GameSupport::getTextPlayLayer(EPlayLayer::kPlayLayer_Ghost), numGhostStart)->getCString();
        m_nodeGhostPlay = m_PlaySelectLayer->getChildByName("nodeNormal")->getChildByName(str);
        
        layer->initalizeSelectPlay(m_nodeGhostPlay, GameData::getInstance()->dataMode.find(LevelManager::s_ID)->second.listExpression[m_currIndexEquation].Answer);

        
    }
    
}

void PlayManager::initGame()
{
    
    
    if(m_list_EquationResult.size() == m_currIndexEquation)
    {
        m_list_EquationRoot = GameData::getInstance()->dataMode.at(LevelManager::s_ID).listExpression;

    }
    m_EquationRoot = m_list_EquationRoot.at(m_currIndexEquation).Question;

    GamePlayConfig::GetInstance()->m_hiddenNumber = m_list_EquationRoot.at(m_currIndexEquation).Answer;

    
    //int size = m_Cloud->getChildrenCount();
    if(m_Cloud->getChildrenCount() == 0)
    {
    Label* label = Label::create(m_EquationRoot, kFont_ADLIBN, 80);
    label->setColor(Color3B(8,120,27));
        
    label->setTag(EPlayComponent::kPlayComponent_Equation);
    label->setPosition(m_Cloud->getContentSize().width / 2, m_Cloud->getContentSize().height / 3);
    
    m_Cloud->addChild(label);
    
    m_Cloud->setVisible(true);
    }
    else
    {
        Label* label = (Label*)m_Cloud->getChildByTag(EPlayComponent::kPlayComponent_Equation);
        label->setString(m_EquationRoot);
    }
}
void PlayManager::calculateTimePlay(Ref* pSender)
{
    m_loadingBar->setPercent(m_loadingBar->getPercent() - m_valueTimeBar);
	m_tempTime--;
    if(m_tempTime >= 0)
        m_timePanel->setTitleText(String::createWithFormat("%d", m_tempTime)->getCString());
}

void PlayManager::update(float dt)
{
    if(m_loadingBar->getPercent() == 0 && m_gameMode != EGameMode::kMode_Easy)
    {
        this->unscheduleUpdate();
        
        m_EGameStatus = EGameStatus::kGhostStatus_Fail;
        OpenResultLayer();
        return;
    }
    
    if(m_playType == EPlayType::kType_Select)
    {
        if (GamePlayConfig::GetInstance()->m_selectNumber != -1)
        {
            m_EGameStatus = GamePlayConfig::GetInstance()->CompareResult() ? EGameStatus::kGhostStatus_Correct : EGameStatus::kGhostStatus_Fail;
        }
        if (m_EGameStatus == EGameStatus::kGhostStatus_Correct || m_EGameStatus == EGameStatus::kGhostStatus_Fail)
        {
            //m_loadingBar->stopAllActions();
            this->unscheduleUpdate();
            Label* label = (Label*)m_Cloud->getChildByTag(EPlayComponent::kPlayComponent_Equation);
            std::string equation = label->getString();
            equation.replace(equation.find("?"), 1, String::createWithFormat("%d", GamePlayConfig::GetInstance()->m_selectNumber)->getCString());
            label->setString(equation);
            OpenResultLayer();
        }
        else if (m_EGameStatus == EGameStatus::kGhostStatus_None)
        {
            if (m_loadingBar->getPercent() == 0)
            {
                m_EGameStatus = EGameStatus::kGhostStatus_Fail;
            }
        }
    }
    
}

void PlayManager::OpenResultLayer()
{
    m_loadingBar->stopAllActions();
    m_PlaySelectLayer->setVisible(false);
    m_PlayAdjustLayer->setVisible(false);
    m_CongratulationsLayer->setVisible(false);
    
    initResult();
    m_ResultLayer->setVisible(true);
    if(m_currIndexEquation == GameData::getInstance()->getMaxNumEquationInLevel(m_gameMode, LevelManager::s_ID) - 1 && m_EGameStatus == EGameStatus::kGhostStatus_Correct)
    {
        auto func = CallFuncN::create(CC_CALLBACK_0(PlayManager::OpenCongratulationsLayer, this));
        m_ResultLayer->runAction(Sequence::create(DelayTime::create(5.0f), func, NULL));
    }
    else
    {
        if(m_gameMode == EGameMode::kMode_Hard)
            m_currIndexEquation++;
        else if(m_EGameStatus == EGameStatus::kGhostStatus_Correct)
            m_currIndexEquation++;
        CallFuncN *func;
        if(m_currIndexEquation < m_list_EquationRoot.size())   // mot sua them hard cho nay
        {
            func = CallFuncN::create(CC_CALLBACK_0(PlayManager::reload, this));
        }
        else
            func = CallFuncN::create(CC_CALLBACK_0(PlayManager::OpenCongratulationsLayer, this));

        m_ResultLayer->runAction(Sequence::create(DelayTime::create(5.0f),func, NULL));
    }
    
}

void PlayManager::initResult()
{
    Label* label = (Label*)m_Cloud->getChildByTag(EPlayComponent::kPlayComponent_Equation);
    std::string equation = label->getString();
    
    if(m_gameMode == EGameMode::kMode_Hard)
    {
        m_list_EquationResult.push_back(equation);
        m_list_AnswerStatus.push_back(m_EGameStatus);
        if(m_EGameStatus == EGameStatus::kGhostStatus_Correct)
        {
            int score = m_tempTime*10;
            m_list_score.push_back(score);

            m_currStar = (m_loadingBar->getPercent() - 1) / 25;
            m_list_star.push_back(m_currStar);
        }
        else
        {
            m_list_star.push_back(0);
            m_list_score.push_back(0);
        }
    }
    else if(m_EGameStatus == EGameStatus::kGhostStatus_Correct)
    {
        m_list_EquationResult.push_back(equation);
        int score = m_tempTime*10;
        m_list_score.push_back(score);
        m_currStar = (m_loadingBar->getPercent() - 1) / 25;
        m_list_star.push_back(m_currStar);

    }
    
    PlayResultLayer* layer = new PlayResultLayer(m_screenSize);
    layer->setPosition(Vec2::ZERO);
    layer->setTag(EPlayLayer::kPlayLayer_Result);
    layer->autorelease();
    this->addChild(layer);
    
    layer->initalize(equation, m_EGameStatus);
    
}

void PlayManager::OpenCongratulationsLayer()
{
    m_ResultLayer->setVisible(false);
    this->getChildByTag(EPlayLayer::kPlayLayer_Result)->removeFromParent();
    initCongratulations();
    m_CongratulationsLayer->setVisible(true);
    timeline::ActionTimeline *timeline = CSLoader::createTimeline("CongratulationLayer.csb");
    
    m_CongratulationsLayer->runAction(timeline);
    timeline->gotoFrameAndPlay(0, 320, false);

    int stars = PlayerInfo::getInstance()->level->getLevelStar(m_gameMode, LevelManager::s_ID);

    if(stars > 0)
    {
        auto func = CallFuncN::create(CC_CALLBACK_0(PlayManager::playStarSound, this));
        auto sequence = Sequence::create(func, DelayTime::create(30.0f/60.0f), NULL);
        this->runAction(Sequence::create(DelayTime::create(80.0f/60.0f), Repeat::create(sequence, stars), NULL));
    }
}

void PlayManager::playStarSound()
{
    SoundManager::getInstance()->playSound(ESound::kSound_Star);
}

void PlayManager::initCongratulations()
{
    
    
    
    PlayCongratulationsLayer* layer = new PlayCongratulationsLayer(m_CongratulationsLayer,m_screenSize); // layer nay dung de quan ly 3 node hien thi cua Congratulation layer trong coco
    
    layer->initalize(m_EGameStatus, m_list_EquationResult, m_currStar);
    
    
    
    if(m_EGameStatus == EGameStatus::kGhostStatus_Correct)
    {
   
    //Save data play
        if (m_EGameStatus == EGameStatus::kGhostStatus_Correct)
        {
            if(!PlayerInfo::getInstance()->level->getLevelEnable(LevelManager::s_mode, LevelManager::s_ID + 1))
            {
                PlayerInfo::getInstance()->level->setLevelEnable(LevelManager::s_mode, LevelManager::s_ID + 1, true);
                PlayerInfo::getInstance()->level->setLevelStar(LevelManager::s_mode, LevelManager::s_ID+ 1, -1);
                if(LevelManager::s_ID + 1 > 2)
                {
                    PlayerInfo::getInstance()->setPlayedTutorial(m_gameMode);
                }
            }
        }
    }
}

void PlayManager::IncreaseGhost(cocos2d::Ref *pSender)
{
    Button* btn= (Button*)pSender;
    if(m_isTutorial)
    {
        if(m_handTutorial->getParent() != btn)
            return;
    }
    int numAdjust = atoi(btn->getTitleText().c_str());
    if(numAdjust > 0)
    {
        Vector<Node*> listPanelGhost = m_nodeGhostPlay->getChildren();

        for(int i= 0; i< numAdjust;i++)
        {
            for(int k = 0; k < listPanelGhost.size();k++)
            {
                Node* panel = listPanelGhost.at(k);
                Vector<Node*> listGhost = panel->getChildren();
                int listSize = (int)listGhost.size();

                for(int j= 0; j < listSize;j++)
                {
                    GhostAdjust* ghost = (GhostAdjust*)listGhost.at(j)->getChildren().at(0);
                    if(!ghost->isVisible())
                    {
                        ghost->setVisible(true);
                        GamePlayConfig::GetInstance()->m_selectNumber++;
                        Label* label = (Label*)m_Cloud->getChildByTag(EPlayComponent::kPlayComponent_Equation);
        
                        CCLOG("%d",GamePlayConfig::GetInstance()->m_selectNumber);
                        std::string equation  = m_EquationRoot;
                        equation.replace(equation.find("?"), 1, String::createWithFormat("%d", GamePlayConfig:: GetInstance()->m_selectNumber)->getCString());
                        label->setString(equation);
                        numAdjust--;
                        
                        SoundManager::getInstance()->playSound(ESound::kSound_Add);
                        
                        checkVisibleButton();
                        if(m_isTutorial)
                            playTutorial();
                        if(numAdjust == 0)
                            return;
                        
                        break;
                    }
                }
            }
        }
    }
}
void PlayManager::DecreaseGhost(cocos2d::Ref *pSender)
{
    Button* btn= (Button*)pSender;
    if(m_isTutorial)
    {
        if(m_handTutorial->getParent() != btn)
            return;
    }
    int numDecrease = atoi(btn->getTitleText().c_str());
    int num = abs(numDecrease);
    numDecrease = num;
    Vector<Node*> listPanelGhost = m_nodeGhostPlay->getChildren();
    
    for(int i= 0; i< num;i++)
    {
        for(int k = 0; k < listPanelGhost.size();k++)
        {
            Node* panel = listPanelGhost.at(k);
            Vector<Node*> listGhost = panel->getChildren();
            int listSize = (int)listGhost.size();

            
            for(int j= 0; j < listSize ;j++)
            {
                    GhostAdjust* ghost = (GhostAdjust*)listGhost.at(j)->getChildren().at(0);
                    if(ghost->isVisible())
                    {
                        
                        ghost->setVisible(false);
                        GamePlayConfig::GetInstance()->m_selectNumber--;
                        CCLOG("%d",GamePlayConfig::GetInstance()->m_selectNumber);
                        Label* label = (Label*)m_Cloud->getChildByTag(EPlayComponent::kPlayComponent_Equation);
                        std::string equation  = m_EquationRoot;
                        equation.replace(equation.find("?"), 1, String::createWithFormat("%d", GamePlayConfig::GetInstance()->m_selectNumber)->getCString());
                        label->setString(equation);
                        num--;
                        
                        SoundManager::getInstance()->playSound(ESound::kSound_Minus);
                        
                        checkVisibleButton();
                        if(m_isTutorial)
                            playTutorial();
                        if(num == 0)
                            return;
                        break;
                    }
                    
            }
        }
    }
}

void PlayManager::Clound_Click(Ref* pSender)
{
    m_EGameStatus = GamePlayConfig::GetInstance()->CompareResult() ? EGameStatus::kGhostStatus_Correct : EGameStatus::kGhostStatus_Fail;
    if(m_isTutorial && m_EGameStatus == EGameStatus::kGhostStatus_Fail)
        return;
    
    if(m_gameMode ==  EGameMode::kMode_Easy && m_EGameStatus == EGameStatus::kGhostStatus_Fail)
    {
        // long am thanh vao day
        SoundManager::getInstance()->playSound(ESound::kSound_Aww);
    }
    else
    {
        SoundManager::getInstance()->playSound(ESound::kSound_PageSwipe);
        this->unscheduleUpdate();
        OpenResultLayer();
    }
    
}
void PlayManager::ReturnLevelScene()
{
    Director::getInstance()->replaceScene(TransitionFade::create(0.5f, LevelManager::createScene()));
}

void PlayManager::checkVisibleButton()
{
    Vector<Node*> listPanelGhost = m_nodeGhostPlay->getChildren();
    int keyGhost = 0;
    int numGhost = 0;
    for(int i= 0; i< listPanelGhost.size();i++)
    {
            Node* panel = listPanelGhost.at(i);
            Vector<Node*> listGhost = panel->getChildren();
            int listSize = (int)listGhost.size();
            
            
            for(int j= 0; j < listSize ;j++)
            {
                GhostAdjust* ghost = (GhostAdjust*)listGhost.at(j)->getChildren().at(0);
                numGhost++;
                if(ghost->isVisible())
                {
                    keyGhost++;
                }
                
            }
        
    }

    if(keyGhost == 0)
    {
        m_btnDecrease->setVisible(false);
         m_btnIncrease->setVisible(true);
    }
    else
    {
        m_btnDecrease->setVisible(true);
        if(keyGhost == numGhost)
        {
            
            m_btnIncrease->setVisible(false);
        }
        else
            m_btnIncrease->setVisible(true);
    }
}
void PlayManager::playTutorial()
{
    
    if(m_playType == kType_Adjust)
    {
            int variance = GamePlayConfig::GetInstance()->m_selectNumber - GamePlayConfig::GetInstance()->m_hiddenNumber;
            if(variance == 0)
            {
                if(m_handTutorial->getParent() != m_Cloud)
                {
                    m_handTutorial->removeFromParent();
                    //m_handTutorial->release();
                    
                    m_Cloud->addChild(m_handTutorial);
                    m_handTutorial->setPosition(m_Cloud->getContentSize().width/2,-m_handTutorial->getContentSize().height*0.3f);
                    m_handTutorial->runAction(RepeatForever::create(Sequence::create(ScaleTo::create(0.2f, 1.1f),ScaleTo::create(0.2f, 0.8f), NULL)));
                }
            }
            else if(variance < 0)
            {
                if(m_handTutorial->getParent() != m_btnIncrease)
                {
                    m_handTutorial->removeFromParent();
                    //m_handTutorial->release();
                    m_btnIncrease->addChild(m_handTutorial);
                    m_handTutorial->setPosition(m_btnIncrease->getContentSize().width/2,-m_handTutorial->getContentSize().height*0.3f);
                    m_handTutorial->runAction(RepeatForever::create(Sequence::create(ScaleTo::create(0.2f, 1.1f),ScaleTo::create(0.2f, 0.8f), NULL)));
                }
            } else
            {
                if(m_handTutorial->getParent() != m_btnDecrease)
                {
                    m_handTutorial->removeFromParent();
                   // m_handTutorial->release();
                    m_btnDecrease->addChild(m_handTutorial);
                    m_handTutorial->setPosition(m_btnDecrease->getContentSize().width/2,-m_handTutorial->getContentSize().height*0.3f);
                    m_handTutorial->runAction(RepeatForever::create(Sequence::create(ScaleTo::create(0.2f, 1.1f),ScaleTo::create(0.2f, 0.8f), NULL)));
                }
            }   
    }
    else
    {
        Vector<Node*> listPanelGhost = m_nodeGhostPlay->getChildren();
        for(int i= 0; i< listPanelGhost.size();i++)
        {
            Node* panel = listPanelGhost.at(i);
            Vector<Node*> listGhost = panel->getChildren();
            int listSize = (int)listGhost.size();
            
            
            for(int j= 0; j < listSize ;j++)
            {
                GhostSelect* ghost = (GhostSelect*)listGhost.at(j)->getChildren().at(0);
                
                if(ghost->getValue() == GamePlayConfig::GetInstance()->m_hiddenNumber)
                {
                    m_handTutorial->removeFromParent();
                    ghost->addComponent(m_handTutorial,10);
                    
                    m_handTutorial->runAction(RepeatForever::create(Sequence::create(ScaleTo::create(0.2f, 1.1f),ScaleTo::create(0.2f, 0.8f), NULL)));
                    return;
                }
                
            }
            
        }

    }
    
}

#pragma region SETTING
void PlayManager::tapSetting(Ref* pSender)
{
    if(m_isTutorial)
        return;
    
	if (!m_isOpenSetting && !m_pnlSetting->isVisible())
	{
        SoundManager::getInstance()->playSound(ESound::kSound_SettingButton);
        
		m_pnlSetting->setVisible(true);
		m_timeline->gotoFrameAndPlay(400, 415, false);
		this->runAction(Sequence::create(DelayTime::create(15.0f / 60.0f),
			CallFuncN::create(CC_CALLBACK_0(PlayManager::setOpenSettingProperty, this)), NULL));
	}
	if (m_isOpenSetting && m_pnlSetting->isVisible())
	{
        SoundManager::getInstance()->playSound(ESound::kSound_SettingButton);

		m_timeline->gotoFrameAndPlay(420, 435, false);
		this->runAction(Sequence::create(DelayTime::create(15.0f / 60.0f),
			CallFuncN::create(CC_CALLBACK_0(PlayManager::setOpenSettingProperty, this)), NULL));
	}
}

void PlayManager::tapHelp(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
}

void PlayManager::tapSound(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
    
    if(CocosDenshion::SimpleAudioEngine::getInstance()->isBackgroundMusicPlaying())
        CocosDenshion::SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
    else
        CocosDenshion::SimpleAudioEngine::getInstance()->resumeBackgroundMusic();

}

void PlayManager::tapMusic(Ref* pSender)
{
    SoundManager::getInstance()->playSound(ESound::kSound_Click);
    
    if(CocosDenshion::SimpleAudioEngine::getInstance()->getEffectsVolume() == 0.0f)
        CocosDenshion::SimpleAudioEngine::getInstance()->setEffectsVolume(1.0f);
    else
        CocosDenshion::SimpleAudioEngine::getInstance()->setEffectsVolume(0.0f);

}

void PlayManager::setOpenSettingProperty()
{
	m_isOpenSetting = !m_isOpenSetting;

	if (!m_isOpenSetting)
		m_pnlSetting->setVisible(false);
}
#pragma endregion

void PlayManager::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event)
{

}